package xyz.robinbingo.turing.dubbo.common.protocol.http;

import xyz.robinbingo.turing.dubbo.common.protocol.invocation.Invocation;
import xyz.robinbingo.turing.dubbo.common.serialize.Serializer;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

/**
 * CustomHttpClient
 *
 * @author Robin
 * @date 2021/1/29 下午3:54
 **/
public class CustomHttpClient {

    public Object send(String hostname, int port, Invocation invocation) {
        HttpRequest request;
        try {
            request = HttpRequest.newBuilder()
                    .uri(new URI("http", null, hostname, port, "/", null, null))
                    .POST(HttpRequest.BodyPublishers.ofByteArray(Serializer.serialize(invocation)))
                    .build();
            HttpClient client = HttpClient.newHttpClient();
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            return response.body();
        } catch (URISyntaxException | InterruptedException | IOException e) {
            e.printStackTrace();
        }

        throw new RuntimeException("send error");
    }
}
